<template>
  <div class="dashboard">
    <div class="dashboard-header">
      <h1>欢迎回来，{{ userStore.user?.full_name }}</h1>
      <p>今天是{{ currentDate }}，祝您学习愉快！</p>
    </div>

    <div class="dashboard-stats">
      <el-row :gutter="20">
        <el-col :span="6">
          <el-card class="stat-card">
            <div class="stat-content">
              <el-icon class="stat-icon" size="32" color="#409EFF">
                <Document />
              </el-icon>
              <div class="stat-info">
                <div class="stat-number">{{ stats.totalExams }}</div>
                <div class="stat-label">总考试数</div>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="stat-card">
            <div class="stat-content">
              <el-icon class="stat-icon" size="32" color="#67C23A">
                <Check />
              </el-icon>
              <div class="stat-info">
                <div class="stat-number">{{ stats.completedExams }}</div>
                <div class="stat-label">已完成</div>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="stat-card">
            <div class="stat-content">
              <el-icon class="stat-icon" size="32" color="#E6A23C">
                <Clock />
              </el-icon>
              <div class="stat-info">
                <div class="stat-number">{{ stats.availableExams }}</div>
                <div class="stat-label">可参加</div>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="stat-card">
            <div class="stat-content">
              <el-icon class="stat-icon" size="32" color="#F56C6C">
                <Star />
              </el-icon>
              <div class="stat-info">
                <div class="stat-number">{{ stats.averageScore.toFixed(1) }}</div>
                <div class="stat-label">平均分</div>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <div class="dashboard-content">
      <el-row :gutter="20">
        <el-col :span="16">
          <el-card>
            <template #header>
              <div class="card-header">
                <span>最近考试</span>
                <el-button type="primary" link @click="$router.push('/exams')">
                  查看更多
                </el-button>
              </div>
            </template>
            <el-table :data="recentExams" style="width: 100%" v-loading="loading">
              <el-table-column prop="title" label="考试名称" />
              <el-table-column prop="start_time" label="开始时间" width="180">
                <template #default="{ row }">
                  {{ formatDateTime(row.start_time) }}
                </template>
              </el-table-column>
              <el-table-column prop="duration" label="时长" width="100">
                <template #default="{ row }">
                  {{ row.duration }}分钟
                </template>
              </el-table-column>
              <el-table-column label="状态" width="100">
                <template #default="{ row }">
                  <el-tag :type="getExamStatusType(row)">
                    {{ getExamStatusText(row) }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column label="操作" width="100">
                <template #default="{ row }">
                  <el-button 
                    type="primary" 
                    size="small"
                    @click="handleTakeExam(row)"
                    :disabled="!canTakeExam(row)"
                  >
                    {{ getActionText(row) }}
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-card>
        </el-col>

        <el-col :span="8">
          <el-card>
            <template #header>
              <div class="card-header">
                <span>最近成绩</span>
                <el-button type="primary" link @click="$router.push('/scores')">
                  查看全部
                </el-button>
              </div>
            </template>
            <div class="score-list" v-loading="loading">
              <div 
                v-for="score in recentScores" 
                :key="score.id"
                class="score-item"
                @click="$router.push(`/score/${score.id}`)"
              >
                <div class="score-info">
                  <div class="score-title">{{ score.exam.title }}</div>
                  <div class="score-date">{{ formatDate(score.submitted_at) }}</div>
                </div>
                <div class="score-value" :class="getScoreClass(score.score)">
                  {{ score.score }}分
                </div>
              </div>
              <el-empty v-if="!recentScores || recentScores.length === 0" description="暂无成绩" />
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useUserStore } from '../stores/user'
import api from '../api'
import { ElMessage } from 'element-plus'
import { useRouter } from 'vue-router'

const userStore = useUserStore()
const router = useRouter()

const loading = ref(false)
const exams = ref([])
const scores = ref([])

const currentDate = computed(() => {
  return new Date().toLocaleDateString('zh-CN', {
    year: 'numeric',
    month: 'long',
    day: 'numeric',
    weekday: 'long'
  })
})

const stats = computed(() => {
  const totalExams = exams.value?.length || 0
  const completedExams = scores.value?.length || 0
  const availableExams = exams.value?.filter(exam => canTakeExam(exam)).length || 0
  const averageScore = scores.value?.length 
    ? scores.value.reduce((sum, score) => sum + score.score, 0) / scores.value.length 
    : 0

  return {
    totalExams,
    completedExams,
    availableExams,
    averageScore
  }
})

const recentExams = computed(() => {
  return exams.value?.slice(0, 5) || []
})

const recentScores = computed(() => {
  return scores.value?.slice(0, 5) || []
})

const loadData = async () => {
  loading.value = true
  try {
    const [examsRes, scoresRes] = await Promise.all([
      api.exams.getAvailableExams(),
      api.scores.getScores({ limit: 10 })
    ])
    exams.value = examsRes.data
    scores.value = scoresRes.data.items
  } catch (error) {
    ElMessage.error('加载数据失败')
  } finally {
    loading.value = false
  }
}

const formatDateTime = (datetime) => {
  return new Date(datetime).toLocaleString('zh-CN')
}

const formatDate = (date) => {
  return new Date(date).toLocaleDateString('zh-CN')
}

const getExamStatusType = (exam) => {
  const now = new Date()
  const startTime = new Date(exam.start_time)
  const endTime = new Date(exam.end_time)
  
  if (now < startTime) return 'info'
  if (now > endTime) return 'danger'
  return 'success'
}

const getExamStatusText = (exam) => {
  const now = new Date()
  const startTime = new Date(exam.start_time)
  const endTime = new Date(exam.end_time)
  
  if (now < startTime) return '未开始'
  if (now > endTime) return '已结束'
  return '进行中'
}

const canTakeExam = (exam) => {
  const now = new Date()
  const startTime = new Date(exam.start_time)
  const endTime = new Date(exam.end_time)
  
  return now >= startTime && now <= endTime
}

const getActionText = (exam) => {
  const now = new Date()
  const startTime = new Date(exam.start_time)
  
  if (now < startTime) return '等待'
  return '参加'
}

const handleTakeExam = (exam) => {
  if (canTakeExam(exam)) {
    router.push(`/exam/${exam.id}/take`)
  }
}

const getScoreClass = (score) => {
  if (score >= 90) return 'excellent'
  if (score >= 80) return 'good'
  if (score >= 60) return 'pass'
  return 'fail'
}

onMounted(() => {
  loadData()
})
</script>

<style scoped>
.dashboard {
  padding: 0;
}

.dashboard-header {
  margin-bottom: 24px;
}

.dashboard-header h1 {
  margin: 0 0 8px 0;
  font-size: 24px;
  color: #303133;
}

.dashboard-header p {
  margin: 0;
  color: #909399;
  font-size: 14px;
}

.dashboard-stats {
  margin-bottom: 24px;
}

.stat-card {
  height: 120px;
}

.stat-content {
  display: flex;
  align-items: center;
  height: 100%;
}

.stat-icon {
  margin-right: 16px;
}

.stat-number {
  font-size: 32px;
  font-weight: bold;
  color: #303133;
  margin-bottom: 4px;
}

.stat-label {
  font-size: 14px;
  color: #909399;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.score-list {
  max-height: 400px;
  overflow-y: auto;
}

.score-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 0;
  border-bottom: 1px solid #f0f0f0;
  cursor: pointer;
  transition: background-color 0.3s;
}

.score-item:hover {
  background-color: #f5f7fa;
}

.score-item:last-child {
  border-bottom: none;
}

.score-title {
  font-size: 14px;
  color: #303133;
  margin-bottom: 4px;
}

.score-date {
  font-size: 12px;
  color: #909399;
}

.score-value {
  font-size: 16px;
  font-weight: bold;
}

.score-value.excellent {
  color: #67c23a;
}

.score-value.good {
  color: #409eff;
}

.score-value.pass {
  color: #e6a23c;
}

.score-value.fail {
  color: #f56c6c;
}
</style>